<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Request;
use app\common\model\Addon as ModelAddon;
use app\common\model\Member as ModelMember;
use app\common\model\AddonDown;
use app\common\model\AddonVersion;
use app\common\model\AddonAutherKey;

class Addon
{
    /*应用列表*/
    public function Index()
    {
        $ModelAddon = new ModelAddon();
        $params = input();
        $page = !empty($params['page']) ? $params['page'] - 1 : 0;
        $limit = !empty($params['limit']) ? $params['limit'] : 1000000;
        $current = !empty($params['current']) ? $params['current'] : 1;
        $orderRaw = !empty($params['raw']) ? $params['raw'] : 'create_time desc';
        $field = 'id,cat,type,name,num,author,sale_price,intro,down,imgs,tags';
        $where = [
            ['is_delete', '=', 0],
            ['status', '=', 1],
        ];
        if (!empty($params['keyword'])) {
            $where[] = ['name|intro|author', 'like', '%' . $params['keyword'] . '%'];
        }
        if (!empty($params['cat'])) {
            $where[] = ['cat', '=', $params['cat']];
        }
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        switch ($current) {
            case 2:
                $where[] = ['sale_price', '<=', 0];
                break;
            case 3:
                $where[] = ['sale_price', '>', 0];
                break;
            case 5:
                $user_id = GetToken('id');
                $source = GetToken("login_source");
                if ($source != 'user' || empty($user_id)) {
                    return BackCode([], 203, '您还没有登录');
                }
                $AddonDown = new AddonDown();
                $Down = $AddonDown->where("user_id='" . $user_id . "' and is_down=1")->field("addon_id")->select()->toArray();
                $ids = '';
                foreach ($Down as $k => $v) {
                    $ids .= $v['addon_id'] . ',';
                }
                $ids = rtrim($ids, ",");
                if ($ids) {
                    $where[] = ['id', 'in', $ids];
                } else {
                    $where[] = ['id', '=', '0'];
                }
                break;
        }

        $rows = $ModelAddon->field($field)->where($where)->orderRaw($orderRaw)->limit($page * $limit, $limit)->select()->toArray();
        foreach ($rows as $k => $v) {
            $img = $this->ChangeImg($v['imgs']);
            $rows[$k]['imgs'] = $img[0];
            $rows[$k]['tags'] = explode(',', $v['tags']);
            $rows[$k]['type'] = !empty($v['sale_price']) ? $v['type'] : 3;
        }
        $total = $ModelAddon->field($field)->where($where)->count();
        $data['rows'] = $rows;//列表数据
        $data['total'] = $total;//总数据
        return BackCode($data);
    }

    public function ChangeImg($img = '')
    {
        $img = !empty($img) ? explode(',', $img) : [];
        foreach ($img as $k => $v) {
            $http = explode('http', $v);
            if (count($http) <= 1) {
                $img[$k] = GetUrl() . $v;
            }
        }
        return $img;
    }

    /*应用详情页面信息*/
    public function Detail()
    {
        $ModelAddon = new ModelAddon();
        $AddonVersion = new AddonVersion();
        $where = "id='" . input("id") . "' and is_delete=0 and status=1";
        $data = $ModelAddon->field("*")->where($where)->find();
        $addon_cat = GetOptions('addon_cat');
        $addon_cat = !empty($addon_cat['rows']) ? $addon_cat['rows'] : [];
        foreach ($addon_cat as $k => $v) {
            if ($v['value'] == $data['cat']) {
                $data['cat'] = $v['label'];
            }
        }
        $data['imgs'] = $this->ChangeImg($data['imgs']);
        $data['tags'] = explode(',', $data['tags']);
        $data['type'] = !empty($data['sale_price']) ? $data['type'] : 3;
        $vField = "version,version_num,id,update_time,content";
        $vWhere = "addon_id='" . input("id") . "' and is_delete=0";
        $data['version'] = $AddonVersion->field($vField)->where($vWhere)->orderRaw('create_time desc')->select()->toArray();
        $data['update_time'] = $data['version'][0]['update_time'];
        $source = GetToken("login_source");
        $data['login'] = 2;
        $data['down_version'] = '';
        if ($source == 'user' && !empty(GetToken("id"))) {
            $data['login'] = 1;
            $AddonDown = new AddonDown();
            $where = "is_down=1 and is_delete=0 and addon_id='" . input("id") . "' and user_id='" . GetToken("id") . "'";
            $Down = $AddonDown->where($where)->orderRaw('CAST(version_id AS UNSIGNED) DESC')->field("version_id")->find();
            if (!empty($Down['version_id'])) {
                foreach ($data['version'] as $k => $v) {
                    if ($v['id'] == $Down['version_id']) {
                        $data['down_version'] = $v['version'];
                    }
                }
            }
        }
        $ModelMember = new ModelMember();
        $data['author_info'] = $ModelMember->where("id='" . $data['author_id'] . "'")->field("nickname,phone,email,avatar,qq_num,wechta_num")->find();
        $addon_list = $ModelAddon->field("id,imgs,name,intro")->where("author_id='" . $data['author_id'] . "' and is_delete=0 and status=1")->orderRaw('CAST(id AS UNSIGNED) DESC')->limit(0, 20)->select()->toArray();
        foreach ($addon_list as $k => $v) {
            $img = $this->ChangeImg($v['imgs']);
            $addon_list[$k]['imgs'] = $img[0];
        }
        $data['author_info']['addon'] = $addon_list;
        return BackCode($data);
    }

    public function Source()
    {
        $data = [];
        $num = 'addon_cat,addon_type';
        $arr = explode(',', $num);
        foreach ($arr as $k => $v) {
            if (!empty($v)) {
                $options = explode('|', $v);
                $data[$options[0]] = GetOptions($v);
            }
        }
        return BackCode($data);
    }

    /*下载压缩包并传输给用户*/
    public function Download()
    {
        $user_id = GetToken('id');
        $order_id = input("order_id");
        $source = GetToken("login_source");
        //$user_id='1797670276910157824';
        //$order_id='1798515142548393984';
        //$source='user';
        if ($source != 'user' || empty($user_id)) {
            return BackCode([], 203, '您还没有登录');
        }
        if (empty($order_id)) {
            return BackCode([], 203, '订单编号不能为空');
        }
        $user = Db::name('member')->where("id='" . $user_id . "' and is_delete=0")->field("id,status")->find();
        if (empty($user['id'])) {
            return BackCode([], 203, '没有这个用户');
        }
        if ($user['status'] != 1) {
            return BackCode([], 203, '账号已封禁');
        }
        $order = Db::name('addon_down')->where("id='" . $order_id . "'")->find();

        if ($order['is_down'] != 1) {
            return BackCode([], 203, '您未支付，不能下载');
        }
        $downIndex = count(explode("http", $order['down_url']));
        $path=App()->getRootPath() . 'public/uploads/addon/' . $order_id . '/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $files=App()->getRootPath() . 'public/uploads/addon/' . $order_id . '/';
        $filePath =$files.'mode.zip';
        $fileToAdd =$files.'info.php';
        if ($downIndex >= 2) {
            $this->downloadZip($order['down_url'], $filePath);//下载远程文件
        } else {
            copy(App()->getRootPath() . 'public' . $order['down_url'], $filePath);//复制文件
        }
        if (!file_exists($filePath)) {
            return BackCode([], 203, '下载失败');
        }
        $addon=Db::name('addon')->where("id='" . $order['addon_id'] . "'")->find();
        $version=Db::name('addon_version')->where("id='" . $order['version_id'] . "'")->find();
        $imgs= $this->ChangeImg($addon['imgs']);
        $info = [
            'order_id' =>$order_id,
            'user_id' =>$user_id,
            'addon_id' =>$order['addon_id'],
            'addon_num' =>$addon['num'],
            'version_id' =>$order['version_id'],
            'version' =>$version['version'],
            'author' =>$addon['author'],
            'name' =>$addon['name'],
            'tags' =>$addon['tags'],
            'imgs' =>$imgs[0],
            'install' => '1',//1待安装2已安装
            'down' =>$addon['down'] ? : 0,
        ];
        $this->SetInfo($info,$fileToAdd);
        $zip = new \ZipArchive;
        $zip->open($filePath, $zip::CREATE);
        if (file_exists($fileToAdd)) {
            $zip->addFile($fileToAdd, $addon['num'].'/config/'.basename($fileToAdd));
        }
        $zip->close();
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename=' . basename($filePath));
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        unlink($filePath);//删除压缩包
        unlink($fileToAdd);//删除配置文件
        rmdir($files);//删除文件夹
        exit;
    }

    //创建订单
    public function DownOrder()
    {
        if (Request()->isAjax() || Request()->isPost()) {
            $user_id = GetToken('id');
            $addonId = input("addon_id");
            $source = GetToken("login_source");
            if ($source != 'user' || empty($user_id)) {
                return BackCode([], 1, '您还没有登录');
            }
            if (empty($addonId)) {
                return BackCode([], 203, '应用参数不能为空');
            }
            $user = Db::name('member')->where("id='" . $user_id . "' and is_delete=0")->field("id,status")->find();
            if (empty($user['id'])) {
                return BackCode([], 203, '没有这个用户');
            }
            if ($user['status'] != 1) {
                return BackCode([], 203, '账号已封禁');
            }
            $addon = Db::name('addon')->where("id='" . $addonId . "' and status=1 and is_delete=0")->find();
            if (empty($addon)) {
                return BackCode([], 203, '无此应用');
            }
            $version = Db::name('addon_version')->where("addon_id='" . $addonId . "' and is_delete=0")->field("id,file_code,version")->orderRaw('CAST(id AS UNSIGNED) DESC')->find();
            if (empty($version)) {
                return BackCode([], 203, '无此版本');
            }
            $where = "addon_id='" . $addonId . "' and is_delete=0 and user_id='" . $user['id'] . "'";
            $downData = Db::name('addon_down')->where($where)->field("id,is_down")->find();
            if (empty($downData)) {
                $downData = [
                    'id' => GetSnowID(),
                    'addon_id' => $addonId,
                    'goods_name' => $addon['name'] . "_" . $version['version'],
                    'version_id' => $version['id'],
                    'user_id' => $user['id'],
                    'sale_price' => !empty($addon['sale_price']) ? $addon['sale_price'] : 0,
                    'is_down' => !empty($addon['sale_price']) ? 2 : 1,
                    'out_trade_no' => GetSnowID(),
                    'sale_type' => $addon['type'],
                    'down_url' => $version['file_code'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                Db::name('addon_down')->insert($downData);
            } else {
                $upData['goods_name'] = $addon['name'] . "_" . $version['version'];
                $upData['version_id'] = $version['id'];
                $upData['update_time'] = date('Y-m-d H:i:s');
                $upData['down_url'] = $version['file_code'];
                if ($downData['is_down'] == 2) {
                    $upData['out_trade_no'] = GetSnowID();
                }
                Db::name('addon_down')->where("id='" . $downData['id'] . "'")->update($upData);
            }
            return BackCode(['id' => $downData['id']]);
        }
    }

    //订单详情
    public function OrderInfo()
    {
        $user_id = GetToken('id');
        $order_id = input("order_id");
        $source = GetToken("login_source");
        if ($source != 'user' || empty($user_id)) {
            return BackCode([], 1, '您还没有登录');
        }
        if (empty($order_id)) {
            return BackCode([], 203, '参数不能为空');
        }
        $user = Db::name('member')->where("id='" . $user_id . "' and is_delete=0")->field("id,status,phone,nickname")->find();
        if (empty($user['id'])) {
            return BackCode([], 203, '没有这个用户');
        }
        if ($user['status'] != 1) {
            return BackCode([], 203, '账号已封禁');
        }
        $order = Db::name('addon_down')->where("id='" . $order_id . "'")->withoutField("down_url")->find();
        $addon= Db::name('addon')->where("id='" . $order['addon_id'] . "'")->field("num")->find();
        $order['addon_num']=$addon['num'];
        $data = [
            'user' => $user,
            'orders' => $order
        ];
        return BackCode($data);
    }

    //支付订单
    public function Pay()
    {
        $user_id = GetToken('id');
        $order_id = input("order_id");
        $pay_type = input("pay_type");
        $source = GetToken("login_source");
        if ($source != 'user' || empty($user_id)) {
            return BackCode([], 203, '您还没有登录');
        }
        if (empty($order_id)) {
            return BackCode([], 203, '订单ID不能为空');
        }
        if (empty($pay_type)) {
            return BackCode([], 203, '支付方式不能为空');
        }
        $user = Db::name('member')->where("id='" . $user_id . "' and is_delete=0")->field("id,status,phone,nickname")->find();
        if (empty($user['id'])) {
            return BackCode([], 203, '没有这个用户');
        }
        if ($user['status'] != 1) {
            return BackCode([], 203, '账号已封禁');
        }
        $order = Db::name('addon_down')->where("id='" . $order_id . "'")->field("goods_name,out_trade_no,sale_price,is_down")->find();
        $sale_price = $order['sale_price'];
        if ($order['is_down'] == 1) {
            return BackCode();
        }
        Db::name('addon_down')->where("id='" . $order_id . "'")->update(['pay_type' => $pay_type]);
        switch ($pay_type) {
            case 2://积分支付
                $add = Db::name('member_integral')->where("member_id='" . $user_id . "' and is_delete=0 and status=2 and type=1")->sum('change_score');
                $delete = Db::name('member_integral')->where("member_id='" . $user_id . "' and is_delete=0 and type=2")->sum('change_score');
                $money = round($add - $delete, 2);
                if ($money < $sale_price) {
                    return BackCode([], 203, '积分不够');
                }
                break;
            case 3://余额支付
                $add = Db::name('member_balance')->where("member_id='" . $user_id . "' and is_delete=0 and status=2 and type=1")->sum('change_score');
                $delete = Db::name('member_balance')->where("member_id='" . $user_id . "' and is_delete=0 and type=2")->sum('change_score');
                $money = round($add - $delete, 2);
                if ($money < $sale_price) {
                    return BackCode([], 203, '余额不够');
                }
                break;
            case 4://微信支付
                $pay = [
                    'body' => $order['goods_name'],
                    'out_trade_no' => $order['out_trade_no'],
                    'total_fee' => $order['sale_price'],
                    'notify' => GetUrl() . '/api/addon/notify/',
                ];
                $ThatPay = new \app\api\service\pay\Weixin();
                $result = $ThatPay->Pay($pay, '1797257239552200704', 'NATIVE');
                if ($result['code'] == 200) {
                    return BackCode($result['data'], 2, '支付信息');
                } else {
                    return BackCode([], 203, $result['msg']);
                }
                break;
            case 5://支付宝支付
                return BackCode([], 203, '暂时不支持');
                break;
        }
        return BackCode([], 203, '支付错误');
    }


    //支付数据回传
    public function Notify()
    {
        $xml = file_get_contents("php://input");
        $xml = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        if (empty($xml)) {
            return ['code' => 203, 'data' => [], 'msg' => '参数错误'];
        }
        $result = json_decode($xml, true);
        if (empty($result['transaction_id'])) {
            return ['code' => 203, 'data' => [], 'msg' => '参数错误'];
        }
        $out_trade_no = $result['out_trade_no'];
        $upData['transaction_id'] = $result['transaction_id'];
        $upData['is_down'] = 1;
        $upData['pay_time'] = date('Y-m-d H:i:s');
        Db::name('addon_down')->where("out_trade_no='" . $out_trade_no . "'")->update($upData);
        echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
    }

    /*用于下载远程文件*/
    public function downloadZip($url = '', $file = '', $timeout = 60)
    {
        if (file_exists($file)) {
            unlink($file);
        }
        $file = empty($file) ? pathinfo($url, PATHINFO_BASENAME) : $file;
        $dir = pathinfo($file, PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir, 0777, true);
        $url = str_replace(" ", "%20", $url);
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $temp = curl_exec($ch);
            if (@file_put_contents($file, $temp) && !curl_error($ch)) {
                return $file;
            } else {
                return false;
            }
        } else {
            $opts = array(
                "http" => array(
                    "method" => "GET",
                    "header" => "",
                    "timeout" => $timeout)
            );
            $context = stream_context_create($opts);
            if (@copy($url, $file, $context)) {
                return $file;
            } else {
                return false;
            }
        }
    }

    public function SetInfo($info = [],$path='')
    {
        $str = '<?php' . PHP_EOL;
        $str .= 'return [' . PHP_EOL;
        foreach ($info as $field => $value) {
            $str .= "    '" . $field . "' =>'" . $value . "'," . PHP_EOL;
        }
        $str .= "];";
        getCreatetxt($path, $str);
    }


}